﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace gcTest
{
    interface TestInterface
    {
        void DoSomething();
    }

    class TestClass : TestInterface
    {
        private Mutex m_Mutex = new Mutex();
        private static long m_Cnt = 0;
        private static int m_ReportCnt = 0;

        private long i_1 = 0;
        private long i_2 = 0;
        private long i_3 = 0;
        private long i_4 = 0;
        private long i_5 = 0;
        private long i_6 = 0;
        private long i_7 = 0;
        private long i_8 = 0;
        private long i_9 = 0;
        private long i_10 = 0;

        public TestClass()
        {
            m_Cnt++;
         //   Interlocked.Increment(ref m_Cnt);
            if (m_ReportCnt++ > 1000)
            {
                Console.WriteLine("cnt: " + m_Cnt);
                m_ReportCnt = 0;
            }
        }

        ~TestClass()
        {
            m_Cnt--;
            //Interlocked.Decrement(ref m_Cnt);
        }

        public void DoSomething()
        {
           Thread.Sleep(1);
            //m_Cnt++;
        }
    }

    class TestClass2 : TestClass
    {
        public void DoSomething2()
        {

        }
    }

    class MyThread
    {
        Thread m_T;
        private static void threadFn()
        {
            Console.WriteLine("Thread started");

            while (true)
            {
                TestInterface o = new TestClass2();
                o.DoSomething();
                byte[] b = new byte[1024*1024];
                b[0] = 1;
            }
        }

        public void Start()
        {
            m_T = new Thread(threadFn);
            m_T.Start();
        }

        public void Join()
        {
            m_T.Join();
        }
    }

    class Program
    {
        private static List<MyThread> m_Threads = new List<MyThread>();


        static void Main(string[] args)
        {
            if (args.Length != 1)
            {
                Console.WriteLine("Usage: a.exe [threads_count]");
                return;
            }

            int cnt = int.Parse(args[0]);
            for (int i = 0; i < cnt; i++)
            {
                MyThread t = new MyThread();
                t.Start();
                m_Threads.Add(t);
            }

            foreach (MyThread t in m_Threads)
            {
                t.Join();
            }
        }
    }
}
